<?php

namespace App\Services\Warehouse\Services;

use App\Services\Warehouse\Interfaces\VendorServiceInterface;
use App\Services\Warehouse\Model\Vendor;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\ApiV2Exception;

class VendorService implements VendorServiceInterface
{
    public function index($request)
    {
        $vendorName = $request['vendorName'] ?? '';
        $size = $request['size'] ?? 50;
        $data = Vendor::query()
            ->when($vendorName, function ($query) use ($vendorName) {
                return $query->where('vendorName', 'like', '%' . $vendorName . '%');
            })
            ->orderBy("updated_at", "desc")
            ->paginate($size);

        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        $vendorName = $request['vendorName'];
        if ($id) {
            $data = Vendor::query()->where('vendorName',$vendorName)->where('id','!=',$id)->first();
            if(!empty($data)){
                throw new ApiV2Exception("供应商名不能重复");
            }
            $data = Vendor::findOrFail($id);
        } else {
            $data = Vendor::query()->where('vendorName',$vendorName)->first();
            if(!empty($data)){
                throw new ApiV2Exception("供应商名不能重复");
            }
            $data = new Vendor();
        }
        $request['user_id'] = Auth::id();
        $data->fill($request)->save();
        return $data->toArray();
    }

    public function get($id)
    {
        return Vendor::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function destroy($id)
    {
        $data = Vendor::findOrFail($id);
        $data->delete();
    }
}
